package com.maodou.core.network

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.io.IOException

suspend inline fun <T> safeApiCall(
    dispatcher: CoroutineDispatcher = Dispatchers.IO,
    crossinline block: suspend () -> T
): NetworkResult<T> = withContext(dispatcher) {
    try {
        val data = block()
        NetworkResult.Success(data)
    } catch (e: HttpException) {
        val code = e.code()
        val message = e.message()
        val body = try { e.response()?.errorBody()?.string() } catch (_: Throwable) { null }
        // 针对常见 HTTP 状态码提供更明确的分组，便于上层分类处理
        NetworkResult.Failure(NetworkError.Http(code, message, body, e))
    } catch (e: IOException) {
        NetworkResult.Failure(NetworkError.Network(e))
    } catch (e: RuntimeException) {
        NetworkResult.Failure(NetworkError.Serialization(e))
    } catch (e: Throwable) {
        NetworkResult.Failure(NetworkError.Unknown(e))
    }
}

// 可选：提供一个扩展，用于将 error body 解析成业务错误模型，便于细粒度提示
inline fun <reified E> NetworkResult.Failure.parseErrorBody(
    crossinline parser: (raw: String) -> E?
): E? {
    val raw = (this.error as? NetworkError.Http)?.body ?: return null
    return runCatching { parser(raw) }.getOrNull()
}